;
class SceneMap {
	_cfg;
	_key;
	_map;
	_layerFirst;
	_path;
	_clip;
	_clips; //裁剪面
	_flats; //压平面
	_autoId;
	_msg; //弹窗信息


	//水面样式
	_styleWater = {
		"color": "#3388FF",
		"baseWaterColor": "rgba(54,122,217,1)", //基础色
		"blendColor": "#123e59", //混合色
		"opacity": 0.4,
		"materialType": "Water",
		"clampToGround": false, //贴地

		"amplitude": 10, //波数
		"frequency": 500, //水波振幅
		"normalMap": "../../img/textures/waterNormals.jpg",
		"materialType": "Water",
		"animationSpeed": 0.03, //速度
		"specularIntensity": 0.5,
		"stRotationDegree": 18.82, //方向
		//...this._styleDistance
	};
	//多边形样式
	_stylePolyGon = {
		"color": "#29cf34",
		"opacity": 0.2,
		"outline": true,
		"outlineWidth": 2,
		"materialType": "Color",
		"clampToGround": false,
		// label: {
		// 	text: dat.name,
		// 	font_size: 18,
		// 	//color: cfg.cname,
		// 	distanceDisplayCondition: true,
		// 	distanceDisplayCondition_far: 500000,
		// 	distanceDisplayCondition_near: 0,
		// }, 
	};


	_styleProjection = {
		"angle": 27.5, //水平张角(度数)
		"angle2": 13.9, //垂直张角(度数)
		"distance": 1890.7, //投射最远距离，单位：米
		"opacity": 1, //透明度 0.0 - 1.0
		"showFrustum": true, //是否显示视椎体框线
		"hiddenAreaColor": "rgba(0,0,0,0.5)", //无视频投影区域的颜色
		"flipx": false, //是否X方向翻转图片
		"flipy": false, //是否Y方向翻转图片
		"url": "http://data.mars3d.cn/file/video/lukou.mp4", //	视频的URL路径,与DOM二选一
		"maskImage": "../../img/textures/video-mask.png", //遮盖融合的图片url地址，可以用于视频的四周羽化效果。
		"heading": 75.2, //方向角 （度数值，0-360度）
		"pitch": -59.2 //俯仰角（度数值，0-360度）
	};

	constructor({
		id,
		cfg,
		tpath,
		api,
		popMsg
	}) {
		//console.log("初始化地图", arguments);
		this._msg = popMsg;

		//倾斜模型地址 发布后使用  /mod/
		this._path = tpath || 'http://192.168.1.254/b3dm/';

		/*center 设置中心*/
		var option2 = {
			maximumScreenSpaceError: 10,
			maximumMemoryUsage: 2000, //最大使用显存
			skipLevelOfDetail: true,
			skipLevels: 14,
			"mouseDownView": {
				"rightDrag": true
			},
			// scene: {
			// 	globe: {
			// 		depthTestAgainstTerrain: true // 不加无法投射到地形上,加上倾斜与地形会融合影响效果
			// 	}
			// }
		};

		//合并属性参数，可覆盖config.json中的对应配置
		var options = mars3d.Util.merge(cfg, option2);
		options['token'] = {
			tianditu: "e5c3984ced09bc1f55e8e1107fdc5a6b",
			baidu: "jTqhUqeeRirqd8musUiYmthqdHDHsiB2",
			gaode: "ee24b622294b5bc659fb92fe81084776",
			ion: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2NjkxN2Y5Ni0wZjgyLTQyZDEtODEzNS0zYTlkN2UwMmU3OTciLCJpZCI6NTM1NDIsImlhdCI6MTYxOTIzMDkzMH0.S3x2FMdIx98KuCq8vN_gkC_PArveXJ5bPBNZ3CEYgtc",
			mapbox: "pk.eyJ1IjoiY25zdW55b3VyIiwiYSI6ImNsMmN5Y2ppaDB0ZGYzam8yZmF2MjVqb3cifQ.FYxirkiZsriqaFw_x0IyAw",
			bing: "Am5SdKm6pNdkP1P5zuUOMZwleCHeA7GD5vuQgZ3xBUbEMBeQ5cQ1WN4B8xqqV1Vt",
			wmts: "83487efb-8fcf-4306-9044-a13ac3097c1a",
		};

		//创建三维地球场景
		let map = new mars3d.Map(id, options);
		map.name = "基础地图图层";

		// 设置鼠标操作习惯,更换中键和右键
		map.changeMouseModel(true);

		var glayer = new mars3d.layer.GraphicLayer();
		glayer.name = "gl图层1";
		map.addLayer(glayer);
		this._layerFirst = glayer;
		//	this.hBindLayerPopup();

		map.on(mars3d.EventType.renderError, function(event) {
			window.location.reload();
		});
		map.on(mars3d.EventType.drawCreated, (t) => {
			this.hOnCreated(t)
		}, this);
		map.on(mars3d.EventType.click, (t) => {
			let g = t.graphic;
			if (g) {
				if (g.listens?.(mars3d.EventType.click))
					return;
				this.hOnClickGraphic(g);
			}
			//console.log("click:", t);
		}, this);

		this._map = map;

		//console.log("右键菜单", map.getContextMenu());
		map.unbindContextMenu();
		/**
		 *  
				map.bindContextMenu([{
					text: "编辑",
					iconCls: 'fa fa-editor',
					children: [],
					callback: r => {
						console.log("编辑", r);
					}
				}]);
				// 关闭事件，大数据addGraphic时影响加载时间
				map.graphicLayer.enabledEvent = false
				tlayer.unbindContextMenu();
				tlayer.closeContextMenu();
				tlayer.unbindHighlight();
				tlayer.unbindPopup();
		 */

		//this.hLayerTilesetAdd('nhsk-repaired/test');

		return this;
	}
	hSetCenter(v) {
		//console.log("设置中心", v);
		this._map.setSceneOptions({
			center: v
		});
	}
	hTestWmts() {
		let url =
			"https://ditu.zjzwfw.gov.cn:443/services/wmts/imgmap/default/oss?request=GetCapabilities&service=WMTS";
		let wmts = new mars3d.layer.WmtsLayer({
			url: url,
			minimumLevel: 7,
			maximumLevel: 19,
			layer: "imgmap",
			style: "default",
			tileMatrixSetID: "esritilematirx",
			crs: "EPSG4490",
			queryParameters: {
				tilematrixset: "esritilematirx"
			},
			headers: {
				"token": "83487efb-8fcf-4306-9044-a13ac3097c1a"
			}
		});
		//	wmts.addTo(this._map);
	}

	hMsg(msg) {
		this._msg(msg);
	}
	hMsgWarn(msg) {
		this._msg({
			message: msg,
			type: 'warning',
		})
	}
	hMsgDone(msg) {
		this._msg({
			message: msg,
			type: 'success',
		})
	}
	hMsgError(msg) {
		this._msg.error(msg);
	}


	hOnClickGraphic(g) {
		//		console.log("clickGraphic:", g);
	}


	/**对象编辑完成
	 * @param {Object} g
	 */
	hOnCreated(g) {
		console.log("drawCreated", g);
		return g;
	}

	hFlyToPoint(gps) {
		//let p = new mars3d.LngLatPoint(gps.lng, gps.lat, 80);
		gps['alt'] = 80;
		//	{"lat":29.284103,"lng":121.376138,"alt":826,"heading":356,"pitch":-36}
		this._map.flyToPoint(gps, {
			radius: 200
		});
	}

	hFlyTo(n) {
		let gs = this._layerFirst.getGraphics();
		let g = null;
		for (var i = 0; i < gs.length; i++) {
			let item = gs[i];
			if (item.name == n) {
				g = item;
				break;
			}
		}
		if (!g) {
			this.hMsgError("定位失败，[" + n + "]");
			return false;
		}
		this._map.flyToGraphic(g, {
			radius: 80
		});
	}
	hFlyToLayer(layerId) {
		console.log("定位",layerId);
		this._map.getLayerById(layerId).flyTo();
	}

	/**模糊查找
	 * @param {Object} attrk 属性
	 * @param {Object} v 相似值
	 */
	hGetLikeV(attrk, v) {
		let layer = this._layerFirst;
		let gs = layer.getGraphics().filter(t => {
			return t.attr[attrk]?.indexOf("v") > -1;
		}); //.map(tt => tt.options.attr.name);
		return gs;
	}


	/**标签 隐藏显示
	 * @param {Object} v flse隐藏,true显示
	 */
	hVisibleLabel(v) {
		let layer = this._layerFirst;
		let gs = layer.getGraphics();
		console.log(layer);
		for (var i = 0; i < gs.length; i++) {
			let g = gs[i];
			if (g.label?.text || g.style.html) {
				g.show = v;
				//console.log("visible:",g.label);
			} else {

			}
		}
	}

	hGetId(n) {
		let ids = this._autoId || [];
		let tn = (n || 'temp-');
		let id = tn + Date.now();
		while (ids.indexOf(id) > -1) {
			id = tn + (Date.now() - 1);
		}
		//console.log(id);
		ids.push(id);
		this._autoId = ids;
		return id;
	};

	hMenu(t, i, c, b) {
		return {
			text: t,
			iconCls: i,
			children: c ? [...c] : [],
			callback: b
		}
	}

	// hAddMenu() { 
	// 	let m = hMenu("图上标记", "fa fa-eyedropper", [
	// 		hMenu('标记矩形', 'fa fa-retweet'),
	// 		hMenu("标记点", 'fa fa-map-marker'), 
	// 	]);
	// 	return m;
	// }


	hGetMap() {
		// gl.on(mars3d.EventType.drawCreated, hCreated, this);
		// gl.on(mars3d.EventType.dblClick, hCreated, this);
		return this._map;
	}

	/**b3dm路径
	 * @param {Object} p
	 */
	hGetPath(p) {
		return `${this._path}${p}/tileset.json`;
	}

	/**添加一个对象到图层
	 * @param {Object} mak
	 */
	hGraphicAdd(mak) {
		this._layerFirst.addGraphic(mak);
	}

	/**创建图层
	 * @param {Object} name 图层名称
	 */
	hCreateLayer(name) {
		var gl = new mars3d.layer.GraphicLayer();
		gl.name = name;
		//this._map.addLayer(gl);
		return gl;
	}

	/**
	 * @param {Object} path 全路径
	 * @param {Object} name 名称
	 * @param {Object} center 重置中心
	 */
	hLoadB3dm(path, name, center) {
		//叠加颜色混合
		let style = {
			"color": {
				"conditions": [
					["true", 'rgba(100, 154, 120, 1.0)']
				]
			},
		};
		let pstyle = {};
		if (center) {
			pstyle['position'] = center;
		}
		var option = {
			url: path,
			scale: 1,
			clip: this._clip,
			//style: style,
			type: "geojson",
			// highlight: {
			// 	"type": "click",
			// 	"color": "#FFFF00"
			// },
			...pstyle,
			skipLevelOfDetail: false, //true:直接加载细节，false:先模糊再清晰
			maximumScreenSpaceError: 10,
		};
		var tlayer = new mars3d.layer.TilesetLayer(option);
		tlayer.name = name;
		this._map.addLayer(tlayer);
		return tlayer.id;
	}
	/**添加b3dm资源
	 * @param {Object} opt {url:"tileset.json"}
	 */
	hLayerTilesetAdd(p, pos) {
		let path = this.hGetPath(p);
		//console.log("loading...", path);

		//叠加颜色混合 
		let style = {
			"color": {
				"conditions": [
					["true", 'rgba(100, 154, 120, 1.0)']
				]
			},
		};

		let pstyle = {};
		if (pos) {
			pstyle['position'] = pos;
		}

		var option = {
			url: path,
			scale: 1,
			clip: this._clip,
			//style: style,
			type: "geojson",
			// highlight: {
			// 	"type": "click",
			// 	"color": "#FFFF00"
			// },
			...pstyle,
			skipLevelOfDetail: true, //true:直接加载细节，false:先模糊再清晰
			maximumScreenSpaceError: 10,
		};
		var tlayer = new mars3d.layer.TilesetLayer(option);
		tlayer.name = p;

		/**
		 * 
		let clip = this.hClip(tlayer);
		let clips = this._clips || [];
		clips.push(clip);
		this._clips = clips;
		this._map.addThing(clip);


		let flat = this.hFlat(tlayer);
		let flats = this._flats || [];
		flats.push(flat);
		this._flats = flats;
		this._map.addThing(flat);
		 */

		this._map.addLayer(tlayer);;


		// flyTo: true, flyTo: true, //加载完成后自动飞行到
		// rightDrag: true,
		//入场动画后再执行flyTo，直接调用flyTo可能造成入场动画失败。
		//tlayer.flyToByAnimationEnd();

		return tlayer;
	}


	hCreateByType(t) {

		// let g = new mars3d.graphic[t.cls]();
		// g.setStyle({
		// 	...t.opt
		// });
		console.log("样式", t);
		this._map.graphicLayer.startDraw({
			type: t.tp,
			'style': {
				'color': '#29cf34',
				'opacity': 0.5,
				'outline': true,
				'outlineWidth': 0x2,
				...t.opt
			},
			'success': (g) => {
				//let positions=g['coordinates'];		
				g.stopDraw();
				//let gjson = g.toJSON();
				//console.log(positions, gjson);

				//let gitem = new mars3d.graphic.BaseGraphic(gjson);
				//gitem.addTo(this._layerFirst);
				//this._map.graphicLayer.stopDraw();
				//this._map.graphicLayer.clear(); 
			}
		})

		//this.hGraphicAdd(g);
		//return g;
	}

	/**水面曲面
	 * 
	 */
	hCreateWater() {
		let id = this.hGetId('curve');
		let opt = {
			"id": id,
			"attr": {
				"id": id,
				"name": "水面",
				"remark": ""
			},
			"fill": true,
			"name": "水面",
			"show": true,
			"type": "closeVurve", //闭合曲面
			"color": "#3388FF",
			"style": this._styleWater,
		};
		this._map.graphicLayer.startDraw(opt);
	};

	/**水面多边形
	 * 
	 */
	hCreateWaterPolyGon(b) {
		let id = this.hGetId('water');
		let opt = {
			"id": id,
			"attr": {
				"id": id,
				"name": "水面",
				"remark": ""
			},
			"fill": true,
			"name": "水面",
			"show": true,
			"type": "polygon", //闭合曲面
			"color": "#3388FF",
			"style": {
				"color": "#3388FF",
				"baseWaterColor": "rgba(54,122,217,1)", //基础色
				"blendColor": "#123e59", //混合色
				"opacity": 0.4,
				"clampToGround": false, //贴地

				"materialType": "Water",
				"amplitude": 10, //波数
				"frequency": 500, //水波振幅
				"normalMap": "../../img/textures/waterNormals.jpg",
				"animationSpeed": 0.03, //速度
				"specularIntensity": 0.5,
				"stRotationDegree": 18.82, //方向,
			},
			// success: (eg) => {
			// 	console.log("水面创建完成", eg);
			// 	b?.(eg);
			// 	//this.hSaveWater(eg);
			// }
		};
		return this._map.graphicLayer.startDraw(opt);
	};

	hCreatePolyGon2(b) {
		let id = this.hGetId('polygon');
		let opt = {
			"id": id,
			"attr": {
				"id": id,
				"name": "水面",
				"remark": ""
			},
			"fill": true,
			"name": "水面",
			"show": true,
			"type": "polygon", //闭合曲面
			"color": "#3388FF",
			"style": {
				"color": "#3388FF50",
				"opacity": 0.2,
				"clampToGround": false, //贴地 

				outline: true,
				outlineColor: '#ff0000',
				outlineWidth: '3',
			},
			success: (eg) => {
				b?.(eg);
			}
		};
		return this._map.graphicLayer.startDraw(opt);
	};

	hCreateWater2(points) {

		const graphic = new mars3d.graphic.Water({
			positions: [points],
			style: {
				//height: 3, // 水面高度 使用此高度坐标中的高度将无效
				"diffHeight": -50,
				normalMap: "../../img/textures/waterNormals.jpg", // 水正常扰动的法线图
				frequency: 250, // 控制波数的数字。
				animationSpeed: 0.01, // 控制水的动画速度的数字。
				amplitude: 10, // 控制水波振幅的数字。
				specularIntensity: 0.7, // 控制镜面反射强度的数字。
				baseWaterColor: "rgba(32,123,140,1)", //基础颜色。#00ffff,#00baff,#006ab4
				blendColor: "rgba(0,26,44,1)", // 从水中混合到非水域时使用的rgba颜色对象。
				opacity: 0.4, // 透明度
				clampToGround: false, // 是否贴地
				"stRotationDegree": 0
			}
		});
		if (!window.gwater) {
			window.gwater = graphic;
		}
		//1，2不适用，都会使倾斜模型溶解错乱
		//1.压平-并不平
		//this.hFlatAddArea(points);

		//2.开挖-水面不透明
		// this.hClipAddAreaPos(points);
		return this._map.graphicLayer.addGraphic(graphic)

	}

	/**载入河流
	 * @param {Object} geojson
	 */
	hLoadWaterByJson(dats) {

		for (var i = 0; i < dats.length; i++) {
			let d = dats[i];
			let points = JSON.parse(d.Json);

			let p2 = points.map(t => {
				return [t[0], t[1], t[2] + .5]
			})
			console.log("river remark:", d.Remark, "gid", d.GId);
			if (+d.Remark) {
				//裁剪面
				this.hClipAddAreaPos(points);
				continue;
			}
			if (+d.GId) {
				//流动河流
				this.hCreateHl(points);
				continue;
			}

			//静止库区
			this.hCreateWater2(p2);
		}
	}

	hCreateHl(points) {
		//console.log("动态河流",points);
		const g = new mars3d.graphic.DynamicRiver({
			positions: points,
			style: {
				image: "../../img/textures/poly-rivers.png",
				width: 200,
				height: .1,
				opacity: 0.3,
				speed: 2
			}
		})
		this._layerFirst.addGraphic(g);
		return g;
	}
	hCreateLine(b) {
		let g = {
			type: "polyline",
			style: {
				width: 4,
				color: '#26aee8'
			},
			success: (eg) => {
				b?.(eg);
			}
		};
		this._map.graphicLayer.startDraw(g);
	}


	hAddBg(json, points) {
		//底面背景 
		json = JSON.parse(JSON.stringify(json));
		let minl = 10000;
		if (isNaN(points)) {
			for (var i = 0; i < points.length; i++) {
				let p = points[i];
				minl = p.alt < minl ? p.alt : minl;
				console.log("min:", p);
			}
			minl = minl - 3;
		} else {
			minl = points;
		}
		let ps = json.geometry.coordinates[0];
		let tps = [];
		for (var i = 0; i < ps.length; i++) {
			//let p  = ps[i];
			let p = json.geometry.coordinates[0][i]; //[2] = minl;
			tps.push([p[0], p[1], minl])
		}
		json.properties.id = json.properties.id + "copy";
		json.properties.style.clampToGround = false;
		json.properties.color = "#eee";
		json.geometry.coordinates[0] = tps;
		this.hAddObject2(json);
		console.log("水面背景", minl, json);
		return minl;
	}

	/**区域创建
	 * @param {Object} name
	 */
	hCreatePolygon(name, b) {

		let id = this.hGetId('area');
		let opt = {
			"id": id,
			"attr": {
				"id": id,
				"name": name,
				"remark": ""
			},
			"fill": true,
			"name": name,
			"show": true,
			"type": "polygon", //闭合曲面
			"color": "#3388FF",
			"style": {
				"clampToGround": true, //贴地

				outline: true,
				outlineColor: '#ff0000',
				outlineWidth: '3',

				"color": "#3388FF",
				"baseWaterColor": "rgba(54,122,217,.51)", //基础色
				"blendColor": "#123e59", //混合色
				"opacity": 0.4,

				// 高亮时的样式
				highlight: {
					type: 'click',
					color: 'rgba(240, 240, 0, 0.5)'
				}
			},
			success: (eg) => {
				b?.(eg);
			}

		};
		this._map.graphicLayer.startDraw(opt);
	}

	hAddByGeoJson(json) {
		let gg = mars3d.Util.geoJsonToGraphics(json)[0];

		//杆子
		let g = this._layerFirst.addGraphic(gg);
		return g;
	}

	hPathGraphic(file) {

		if (file.indexOf(".") == -1) {
			return `${this._path}s/${file};tileset.json`;
		}
		return `${this._path.replace("JD","ReadFile")}/${file}`; //gwtt.glb`;
	}
	/**重置模型资源
	 * @param {Object} g
	 * @param {Object} file
	 */
	hResetGraphic({
		g,
		file,
		back
	}) {

		let dat = {
			...g.options.attr.dat
		};
		if (dat.mod == file) {
			back?.(g);
			//--------------------------------------------0.未做更改
			return;
		}
		let isMod = file.indexOf(".") > -1;
		let prevIsMod = g.type == "model";
		let p = this.hCenter(JSON.parse(dat?.points));
		let url = this.hPathGraphic(file);
		console.log("模型切换", dat, url);
		if (isMod && prevIsMod) {
			/*-------------------------------------------1.同为单模型*/
			g.setOptions({
				style: {
					url: url
				}
			});
			g.reload();
			back?.(g);
			return;
		}
		if (!isMod && !prevIsMod) {
			/*-------------------------------------------2.同为多模型*/
			g.setOptions({
				url: url
			});
			g.reload();
			back?.(g);
			return;
		}
		dat.mod = file;
		g.destroy();


		/*-------------------------------------------3.删除重建模型*/
		this.hAddGraphic({
			position: p,
			dat: dat,
			back: back
		});
	}
	hAddGraphic({
		headers,
		position,
		dat,
		back
	}) {
		let isMod = dat.mod.indexOf(".") > -1;
		if (isMod) {
			this.hAdd_Model(headers, position, dat, back);
			return;
		}
		this.hAdd_b3dm(headers, position, dat, back);
	}

	hAdd_b3dm(headers, position, dat, back) {
		let path = this.hPathGraphic(dat.mod);
		let p = position;
		let ll = {
			lng: p[0],
			lat: p[1],
			alt: p[2]
		};
		let rot = JSON.parse(dat.rot);
		//console.log("文件", dat, path, position);
		var option = {
			name: dat.name,
			url: path,
			scale: dat.scale || 0,
			attr: {
				dat: dat
			},
			...headers,
			type: "geojson",
			position: ll,
			rotation: {
				x: rot.x,
				y: rot.y,
				z: rot.z, // dat.heading || 0
			},
			skipLevelOfDetail: false, //true:直接加载细节，false:先模糊再清晰
			maximumScreenSpaceError: 30 //越大加载越快
		};
		//	console.log("参数：", option);
		var tlayer = new mars3d.layer.TilesetLayer(option);

		this._map.addLayer(tlayer);
		back?.(tlayer);
		// tlayer.on("load", r => {
		// 	let radius = r.layer.boundingSphere.radius;
		// });
	};
	hAdd_Model(headers, position, dat, back) {
		let url = this.hPathGraphic(dat.mod);
		let rot = JSON.parse(dat.rot);
		let json = {
			"type": "Feature",
			"properties": {
				name: dat.name,
				dat: dat,
				"type": "model",
				"style": {
					"url": url,
					"heading": rot.z || 0, // dat.heading || 0,
					"pitch": rot.x || 0,
					"roll": rot.y || 0,
					"scale": dat.scale || 1,
					...headers
				}
			},
			"geometry": {
				"type": "Point",
				"coordinates": position
			}
		}
		let g = this.hAddByGeoJson(json);
		back?.(g);
	}



	hDistance(points) {
		let dis = new mars3d.graphic.DistanceMeasure({
			positions: points
		});
		return dis.distance;
	}
	/**计算居中位置
	 * @param {Object} ps
	 */
	hCenter(ps) {
		let lat = 0,
			lng = 0,
			alt = 0,
			count = ps.length;
		for (var i = 0; i < count; i++) {
			lng += ps[i][0];
			lat += ps[i][1];
			alt += ps[i][2];
		}
		lat /= count;
		lng /= count;
		alt /= count;
		return [lng, lat, alt];
	}

	/** 创建区域
	 * @param {String} name
	 * @param {Object} dat
	 * @param {lanlngArray} points
	 * @param {Function} back
	 */
	hAddArea({
		name,
		dat,
		points,
		back,
		done
	}) {
		/*
	 points = [
			[119.969947, 30.288876, 13.1],
			[119.972149, 30.289257, 13.1],
			[119.972445, 30.286141, 13.7],
			[119.97025, 30.2856, 14.3]
		];
		*/
		let json = {
			"type": "Feature",
			"properties": {
				"name": name,
				...dat,
				"type": "polygon",
				"style": {
					"color": "#29cf34",
					"opacity": 0.5,
					"outline": true,
					"outlineWidth": 2,
					"materialType": "Color",
					"clampToGround": false,
					"highlight": {
						"type": "click",
						"color": "#0653cf"
					},
				}
			},
			"geometry": {
				"type": "Polygon",
				"coordinates": [points]
			}
		}

		let g = this.hAddByGeoJson(json);


		if (back) {
			//dblClick
			g.on(mars3d.EventType.dblClick, r => back?.(r));
		}

		done?.(g);
	}

	hAddDiv({
		position,
		text,
		file,
		back
	}) {
		//创建 div
		//计算居中位置 
		const gsw = new mars3d.graphic.DivGraphic({
			position: position,
			name: text,
			attr: {},
			allowDrillPick: true,
			style: {
				...this.divStyle,
				html: this.hDivHtml(text, 'divArea', file)
			}
		});
		this._layerFirst.addGraphic(gsw);
		gsw.on('click', r => {
			r?.graphic.flyTo({
				radius: 70
			});
			console.log("divclick", r);
		})
		back?.(gsw);
	}


	// distanceDisplayCondition: {
	// 			near: 0, // 按视距距离显示
	// 			far: 100000
	// 		},
	/**dom string
	 * @param {String} text 显示文本
	 * @param {String} c styelClass
	 */
	hDivHtml(text, c, file) {
		return `<div class="mak ${c}" title="${text}" >  
							<div class="mak-box"> 
									<img src="imgs/mapIcon/${file}" height="30"> 
								<span>${text}</span>
							</div>
						</div>`;
	};
	divStyle = {
		distanceDisplayCondition: false,
		scale: 1,
		scaleByDistance: true, //距离缩放
		scaleByDistance_near: 500,
		scaleByDistance_far: 100000,
		scaleByDistance_farValue: 2,
		scaleByDistance_nearValue: 1,
		css_transform_origin: 'center bottom 0px', //缩放对齐方式
		horizontalOrigin: 0, //Cesium.HorizontalOrigin.CENTER;
		verticalOrigin: 1, //Cesium.VerticalOrigin.BOTTOM
		clampToGround: false,
		highlight: { // 高亮时的样式
			type: mars3d.EventType.click,
			className: "is-active"
		}
	};

	/**载入投影
	 * @param {Object} dats
	 */
	hLoadProjectionByJson(dats) {
		let d = dats[0];
		let json = d.Json;
		let geojson = JSON.parse(json);
		console.log("投影数据", geojson);
		let vel = this.hVideoEl();
		geojson.properties.style = {
			material: vel,
			stRotationDegree: 90, // 视频旋转角度
			clampToGround: true
		};
		//添加单个geojson为graphic
		const g = mars3d.Util.geoJsonToGraphics(geojson)[0];
		g.attr.Gid = d.ID;
		if (!g) {
			console.log("创建失败", d);
			return;
		}
		this._layerFirst.addGraphic(g);
	}

	/**区域对象
	 * @param {Object} geojson
	 */
	hAddObject(geojson) {

		const g = mars3d.Util.geoJsonToGraphics(geojson)[0];

		if (!g) {
			console.log("创建失败", geojson);
			return null;
		}
		g.style.color = "rgba(240, 240, 0, 0.5)";
		return this._layerFirst.addGraphic(g);
	}
	hAddObject2(geojson) {

		const g = mars3d.Util.geoJsonToGraphics(geojson)[0];
		if (!g) {
			console.log("创建失败", geojson);
			return null;
		}
		return this._layerFirst.addGraphic(g);
	}

	/**创建多边型裁剪
	 * 
	 */
	hClipPolyGon(back) {
		var opt = {
			"id": "temp-clip-PolyGon",
			"type": "polygon",
			"style": this._stylePolyGon,
			success: (g) => {
				let parr = g['coordinates'];
				if (back) {
					back(parr);
				}
				g.remove(true);
			}
		};
		this._map.graphicLayer.startDraw(opt);
	}


	/**创建用户标签
	 * @param {Object} lbtype
	 * @param {Object} b
	 */
	hCreateUserLabel(lbtype, b) {
		let style = {
			image: lbtype.ilast,
			horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
			verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
			width: '30',
			height: '30',
			label: {
				//不需要文字时，去掉label配置即可  
				background: true,
				backgroundColor: "#44ce62",
				backgroundOpacity: 0.7,
				backgroundPadding: new Cesium.Cartesian2(8, 4),
				distanceDisplayCondition: true,
				scaleByDistance: true,
				distanceDisplayCondition_far: 6000,
				distanceDisplayCondition_near: 1,

				text: lbtype.label,
				color: "#eee",
				font_family: "微软雅黑",
				font_size: "16",
				pixelOffsetY: -50,
				outline: false,
			}
		};

		let attr = {
			name: lbtype.label,
			gid: '', //graphic id
			projId: '', //投影id
			Other: '',
			DatType: "标签_" + lbtype.key_self,

		}
		let opt = {
			"id": this.hGetId(attr.name),
			"attr": attr,
			"name": attr.name,
			"show": true,
			"type": "billboard",
			"style": style,
			success: (eg) => {
				b?.(eg);
			}
		};
		this._map.graphicLayer.startDraw(opt);
	}

	hVideoEl() {
		let vpath = "../../file/lukou.mp4";
		let videoElement = mars3d.DomUtil.create("video", "", document.body)
		videoElement.setAttribute("muted", "muted")
		videoElement.setAttribute("autoplay", "autoplay")
		videoElement.setAttribute("loop", "loop")
		videoElement.setAttribute("crossorigin", "")
		videoElement.setAttribute("controls", "")
		videoElement.style.display = "none";

		var mp4Source = mars3d.DomUtil.create("source", "", videoElement);
		mp4Source.setAttribute("src", vpath);
		mp4Source.setAttribute("type", "video/mp4");

		setTimeout(() => {

			videoElement.play();
		}, 3000);

		return videoElement;
	}
	hSetProjection(parr, domVideo) {
		let vel = domVideo || this.hVideoEl();

		console.log(parr);
		let glayer = this._layerFirst; //this._map.graphic

		let ln = 0.0002,
			la = 0.0002;
		var graphic = new mars3d.graphic.PolygonEntity({
			positions: parr,
			styleType: "video", // 属性编辑框使用
			style: {
				material: vel,
				stRotationDegree: 90, // 视频旋转角度
				clampToGround: true
			},
			attr: {
				id: id,
				remark: "投影"
			}
		})
		glayer.addGraphic(graphic);

		return graphic;
	}
	/**投影
	 * [lng,lat,alt]
	 */
	hCreateProjection2(id, pos) {
		let geojson = {
			"type": "Feature",
			"properties": {
				"name": "",
				"remark": "投影1",
				"id": "m-c917cc49-f23e-42df-b99c-e1eccfeda7bf",
				"type": "video3D",
				"style": {
					...this._styleProjection
				}
			},
			"geometry": {
				"type": "Point",
				"coordinates": [...pos]
			}
		};
		const g = mars3d.Util.geoJsonToGraphics(geojson)[0];
		if (!g) {
			console.log("创建失败", d);
			return;
		}
		g.attr.id = id;
		this._layerFirst.addGraphic(g);
		return g;
	}
	hCreateProjection(p, domVideo) {
		let vel = domVideo || this.hVideoEl();
		let id = this.hGetId(this._tp.projn);
		console.log(p);
		let glayer = this._layerFirst; //this._map.graphic

		let ln = 0.0002,
			la = 0.0002;
		var graphic = new mars3d.graphic.PolygonEntity({
			id: id,
			positions: [
				[p[0] + ln, p[1] + la, 130],
				[p[0] + ln, p[1] - la, 130],
				[p[0] - ln, p[1] - la, 130],
				[p[0] - ln, p[1] + la, 130],
			],
			styleType: "video", // 属性编辑框使用
			style: {
				material: vel,
				stRotationDegree: 90, // 视频旋转角度
				clampToGround: true
			},
			attr: {
				id: id,
				remark: "投影"
			}
		})
		glayer.addGraphic(graphic);

		return graphic;
	}
	hCreateProjection3(p, domV) {
		let mask = "../../img/textures/video-mask.png";
		const video3D = new mars3d.graphic.Video3D({
			//	position: cameraPosition,
			targetPosition: p,
			style: {
				container: videoElement,
				maskImage: mask, // 羽化视频四周，融合更美观
				angle: 46.3,
				angle2: 15.5,
				heading: 178.5,
				pitch: -49.5,
				showFrustum: true
			}
		})
		this._layerFirst.addGraphic(video3D)
	}


	/**开挖
	 * 
	 */
	hClip(tilesetLayer) {
		//TerrainClip
		let terrainClip = new mars3d.thing.TilesetClip({
			diffHeight: 1000, // 井的深度
			eventParent: true,
			enable: true,
			image: "../../img/textures/poly-stone.jpg",
			imageBottom: "../../img/textures/poly-soil.jpg",
			splitNum: 200, // 井边界插值数
			layer: tilesetLayer
		});
		return terrainClip;
	}
	/**添加截面区域
	 * @param {Object} eg
	 */
	hClipAddArea(eg) {
		return this.hClipAddAreaPos(eg.coordinates);
	}
	hClipAddAreaPos(parr) {
		//区域补面
		const g = new mars3d.graphic.PolygonEntity({
			positions: parr,
			style: {
				color: "#122128",
				opacity: .6,
			},
		});
		this._layerFirst.addGraphic(g);

		//区域截面
		let clips = this._clips;
		let id = null;
		for (var i = 0; i < clips.length; i++) {
			let clip = clips[i];
			let o = clip.addArea(parr, {
				diffHeight: 100
			});
			id = o.id;
			//console.log("clip", o);
		}
		return id;
	}
	hClipRemove(id) {
		let clips = this._clips;
		for (var i = 0; i < clips.length; i++) {
			clips[i].removeArea(id);
		}
	}

	/**压平
	 * 
	 */
	hFlat(tilesetLayer) {
		let flat = new mars3d.thing.TilesetFlat({
			layer: tilesetLayer
		});
		return flat;
	};
	/**添加压平区域
	 * @param {Object} parr
	 */
	hFlatAddArea(parr) {
		console.log("压平区域", parr);
		let flats = this._flats;
		for (var i = 0; i < flats.length; i++) {
			let flat = flats[i];
			flat.addArea(parr);
		}
	}
	/**更新压平高度
	 * @param {Object} h
	 * @param {Object} id
	 */
	hFlatHeight(h, id) {
		let flats = this._flats;
		for (var i = 0; i < flats.length; i++) {
			let flat = flats[i];
			flat.height = h;
		}
		console.log("高度", h);
	}

	/**绘制矩形
	 * 
	 */
	hDrawRect(back) {
		let map = this._map;

		map.graphicLayer.clear()
		// 绘制矩形
		map.graphicLayer.startDraw({
			type: "rectangle",
			style: {
				fill: true,
				color: "rgba(255,255,0,0.2)",
				outline: true,
				outlineWidth: 2,
				outlineColor: "rgba(255,255,0,1)"
			},
			success: function(g) {
				back(g);
			}
		})
	}


	/**
			//加不上
				hAddMenu: g => {
			return;
			console.log("添加事件", g);
			let menu = [
				map.hMenu("编辑", "fa fa-eyedropper", false, r => {
					console.log("编辑", r);
				})
			];
			// g.setOptions({
			// 	hasMoveEdit: true,
			// 	hasEdit: true,
			// 	hasEditContextMenu: true,
			// 	hasEditScale: true,
			// 	hasEditRotate: true,
			// 	contextmenuItems:menu,
			// });
			g.bindContentMenu(menu);
			console.log("添加菜单", g);
		},
	 */
}